package com.mfl.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mfl.common.PageResult;
import com.mfl.mapper.CollectMapper;
import com.mfl.mapper.KYCourseBookMapper;
import com.mfl.mapper.KYCourseVideoMapper;
import com.mfl.pojo.dto.CollectDTO;
import com.mfl.pojo.dto.CollectPageQueryDTO;
import com.mfl.pojo.entity.Collect;
import com.mfl.pojo.entity.KYCourseBook;
import com.mfl.pojo.entity.KYCourseVideo;
import com.mfl.pojo.vo.CollectPageQueryVO;
import com.mfl.service.CollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class CollectServiceImpl implements CollectService {

    @Autowired
    private CollectMapper collectMapper;
    @Autowired
    private KYCourseBookMapper kyCourseBookMapper;
    @Autowired
    private KYCourseVideoMapper kyCourseVideoMapper;

    /**
     * 添加收藏
     * @param collectDTO
     */
    @Override
    public void add(CollectDTO collectDTO) {
        Collect collect = Collect.builder()
                .userId(collectDTO.getUserId())
                .type(collectDTO.getType())
                .typeId(collectDTO.getTypeId())
                .createTime(LocalDateTime.now())
                .build();
        collectMapper.add(collect);
    }

    /**
     * 删除收藏
     * @param collectDTO
     */
    @Override
    public void delCollect(CollectDTO collectDTO) {
        Collect collect = Collect.builder()
                .userId(collectDTO.getUserId())
                .type(collectDTO.getType())
                .typeId(collectDTO.getTypeId())
                .build();
        collectMapper.delCollect(collect);
    }

    /**
     * 分页查询收藏
     * @param collectPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(CollectPageQueryDTO collectPageQueryDTO) {
        PageHelper.startPage(collectPageQueryDTO.getPage(), collectPageQueryDTO.getPageSize());
        Page<CollectPageQueryVO> page = collectMapper.pageQuery(collectPageQueryDTO);
        page.getResult().forEach(item -> {
            if(collectPageQueryDTO.getType().equals("book")){
                KYCourseBook book = kyCourseBookMapper.getCourseBookById(item.getTypeId());
                item.setCover(book.getCover());
                item.setTitle(book.getBookName());
            }else if(collectPageQueryDTO.getType().equals("video")){
                KYCourseVideo video = kyCourseVideoMapper.getCourseVideoById(item.getTypeId());
                item.setCover(video.getCover());
                item.setTitle(video.getCourseName());
            }
        });
        return new PageResult(page.getTotal(), page.getResult());
    }
}
